package top.riske.animalhazardassessment.common.filter.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.ContentCachingRequestWrapper;
import top.riske.animalhazardassessment.common.utils.RequestUtils;

/**
 * 拦截所有请求，输出所有日志信息
 */
@Slf4j
@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取客户端 IP
        String clientIp = RequestUtils.getRealIp(request);

        // 获取请求 URL
        String requestUrl = request.getRequestURL().toString();

        // 获取请求参数（GET/POST）
        String queryString = request.getQueryString(); // GET 参数
        String requestBody = "";

        // 如果是 POST/PUT 请求，读取 body（需要缓存 request）
        if (request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper cachedRequest = (ContentCachingRequestWrapper) request;
            byte[] content = cachedRequest.getContentAsByteArray();
            if (content.length > 0) {
                requestBody = new String(content, cachedRequest.getCharacterEncoding());
            }
        }

        // 打印日志
        log.info("Request IP: {}, URL: {}, Query Params: {}, Body: {}",
                clientIp, requestUrl, queryString, requestBody);

        return true;
    }

}
